<?php
namespace app\index\controller\tan;
 
use think\Request;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Writer\Ods;

/**
 * 下载
 */
class DownloadFile {
    private $Spreadsheet;
    /**
     *设置下载的文件格式
     * @var  $type
     */
    private $type="Xlsx";
    public function __construct(Spreadsheet $Spreadsheet,Request $Request) {
        $this->Spreadsheet=$Spreadsheet;
        $type =(string)$Request->get("DownloadType");
        preg_match('/^[a-zA-z]{1,10}$/', $type, $matches);
        if(! empty($matches)){
            $this->type=$type;
        }
        ini_set('memory_limit', '128M');
        
    }
    /**
     * 下载
     * @param array $data    数据
     * @param array $ArrKey  要保留的key和value，并且由该参数的key排序
     */
    public function download($data ,$ArrKey){

        $datas[]= array_values($ArrKey);
        $keys= array_keys($ArrKey);
        foreach ($data as $key=> $arr ){
            foreach($keys as $v){
                if(is_array($arr)){
                    $datas[$key+1][$v]= empty($arr[$v])? "":$arr[$v] ;
                } else {
                    $datas[1][$v]= empty($data[$v])?"":$data[$v];
                }
            }
        }
        $this->Spreadsheet
            ->getActiveSheet()
            ->fromArray($datas,null,"A1");
        call_user_func([$this,$this->type]);
    }

        /**
     * xlsx格式下载
     */
    public function Xlsx(){
        $writer = new Xlsx($this->Spreadsheet);
        $name=date("Y-m-d H:i:s");
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $name . '.xlsx"');
        header('Cache-Control: max-age=0');
        $writer->save('php://output');
    }
    public function Ods(){
        $writer = new Ods($this->Spreadsheet);
        $name=date("Y-m-d H:i:s");
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $name . '.Ods"');
        header('Cache-Control: max-age=0');
        $writer->save('php://output');
    }
    /**
     * Xls格式下载
     */
    public function Xls(){
        
        
    }
    /**
     * csv格式下载
     */
    public function Csv(){
        
    }
    /**
     * Pdf格式下载
     */
    public function Pdf(){
        
    }

    /**
     * 
     * @param type $name
     * @param type $arguments
     */
    public function __call($name, $arguments) {
        $this->Xlsx();#当不存在时，默认Xlsx格式
    }    
}
